#pragma once

#include <QtWidgets/QWidget>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include "ui_xrtc_client.h"

#include "xrtc/ixrtc_engine.h"

class XRTCClient : public QWidget,
                   public xrtc::XRTCEngineObserver
{
    Q_OBJECT

public:
    XRTCClient(QWidget *parent = nullptr);
    ~XRTCClient();

public Q_SLOTS:
    void ClickBtnJoin();
    void ClickBtnLeave();

protected:
    virtual void closeEvent(QCloseEvent* event) override;

private:
    void InitStreamWindows(int num);
    void InitDeviceInfo();
    void ConnectSlot();
    void SetTips(const std::string& tips, bool is_error = false);
    
    void OpenCamSource();
    void CloseCamSource();

    void OpenPreview();
    void ClosePreview();

    void resizeEvent(QResizeEvent* event) override;

    // XRTCEngineObserver
    virtual void OnVideoSourceStartEvent(xrtc::IXRTCMediaSource* video_source,
        xrtc::XRTCError err) override;
    
    virtual void OnVideoSourceStopEvent(xrtc::IXRTCMediaSource* video_source,
        xrtc::XRTCError err) override;
    
    virtual void OnPushStreamState(xrtc::IXRTCPusher* pusher,
        xrtc::XRTCStreamState state) override;
    
    virtual void OnStartPushEvent(xrtc::IXRTCPusher* pusher,
        xrtc::XRTCError err) override;
    
    virtual void OnStopPushEvent(xrtc::IXRTCPusher* pusher,
        xrtc::XRTCError err) override;

    virtual void OnPullStreamState(xrtc::IXRTCPlayer* player,
        xrtc::XRTCStreamState state) override;
    
    virtual void OnStartPullEvent(xrtc::IXRTCPlayer* player,
        xrtc::XRTCError err) override;
    
    virtual void OnStopPullEvent(xrtc::IXRTCPlayer* player,
        xrtc::XRTCError err) override;

    virtual void OnRemotePeerLeaveEvent() override;

private:
    Ui::XRTCClientClass ui;
    QHBoxLayout* bootomLayout = nullptr;
    int video_width_ = 800;
    int video_height_ = 600;
    std::atomic<bool>in_room_ = { false };

    xrtc::IXRTCEngine* xrtc_engine_ = nullptr;
    xrtc::IXRTCVideoSource* cam_source_ = nullptr;
    xrtc::IXRTCPreview* local_video_preview_ = nullptr;
    xrtc::IXRTCPusher* xrtc_pusher_ = nullptr;
    xrtc::IXRTCPlayer* xrtc_player_ = nullptr;
};
